package com.ssm.controller;

import com.ssm.pojo.Good;
import com.ssm.service.GoodService;
import com.ssm.service.ShoppingcartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: exercise1_online_shopping
 * @author: qin haojun
 * @create: 2021-02-14 18:22
 */
@Controller

public class GoodController {

    @Autowired
    GoodService goodService;

    @RequestMapping("/goodlist")
    public ModelAndView goodlist(HttpServletRequest request,
                                 @RequestParam(value = "keyWord",required = false)String keyWord)
            throws Exception{
        ModelAndView modelAndView=new ModelAndView();

        //要想进入此页面，需要先验证是否登陆了
        if(!isLogin(request)){
            request.getSession().setAttribute("status","请先进行登陆");
            modelAndView.setViewName("redirect:/user/login");
            return modelAndView;
        }

        //获取商品信息
        List<Good> goodList;
        if(keyWord!=null&&!keyWord.equals("")){
            goodList=goodService.selectGoodsByKeyWord(keyWord);
        }
        else {
            goodList=goodService.getGoodList();
        }
        modelAndView.addObject("goodList",goodList);
        modelAndView.setViewName("good/goodlist");

        return modelAndView;
    }

    /**
     * 通过gid获得物品信息，并前往物品详情页面
     * @param gid
     * @return
     * @throws Exception
     */
    @RequestMapping("/good")
    public ModelAndView goodDetail(@RequestParam(value = "gid")Integer gid,HttpServletRequest request)
            throws Exception{
        ModelAndView modelAndView=new ModelAndView();
        //要想进入此页面，需要先验证是否登陆了
        if(!isLogin(request)){
            request.getSession().setAttribute("status","请先进行登陆");
            modelAndView.setViewName("redirect:/user/login");
            return modelAndView;
        }




        Good good=goodService.selectGoodById(gid);
        modelAndView.addObject("good",good);
        modelAndView.setViewName("good/detailGood");

        //还有，获得这个商品的销售额
        Integer sellCnt=goodService.getSellCnt(gid);
//        Integer sellCnt=37;
        modelAndView.addObject("sell_cnt",sellCnt);

        return modelAndView;
    }

    private boolean isLogin(HttpServletRequest request){
        return request.getSession().getAttribute("user")==null?false:true;
    }

}
